package edu.jmu.proxyjdk;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;;

public class MyBeanFactoryCGLIB {
	public static UserDao getBean() {
		//1.准备目标类
		final UserDao userDao = new UserDaoImpl();
		//2.创建切面实现类
		final MyAspect myAspect = new MyAspect();
		//3.生成代理类，CGLIB在运行时，生成指定对象的子类，并增强
		//3.1核心类
		Enhancer enhancer = new Enhancer();
		//3.2确定需要增强的类
		enhancer.setSuperclass(userDao.getClass());
		//3.3 添加回掉函数
		enhancer.setCallback(new MethodInterceptor() {
			
			@Override
			public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
				myAspect.myBefore();
				Object object = method.invoke(userDao,args);
				myAspect.myAfter();
				return object;
			}
		});
		
		UserDao userDaoProxy = (UserDao)enhancer.create();
		return userDaoProxy;
	}
}
